package com.app.oral.service.impl

import com.app.oral.dao.UserMapper
import com.app.oral.dao.UserSessionMapper
import com.app.oral.model.*
import com.app.oral.service.UserService
import com.app.oral.service.ExerciseRecordService
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional
import java.time.LocalDateTime

@Service
class UserServiceImpl(
    private val userMapper: UserMapper,
    private val userSessionMapper: UserSessionMapper,
    private val exerciseRecordService: ExerciseRecordService
) : UserService {

    companion object {
        private val logger = LoggerFactory.getLogger(UserServiceImpl::class.java)
    }

    override fun getOrCreateUser(openid: String, nickname: String, avatarUrl: String): User {
        var user = userMapper.findByOpenid(openid)
        if (user == null) {
            val newUser = User(
                openid = openid,
                nickname = nickname,
                avatarUrl = avatarUrl,
                accountStatus = AccountStatus.INCOMPLETE
            )
            userMapper.insert(newUser)
            user = userMapper.findByOpenid(openid)
        }
        return user!!
    }

    override fun completeProfile(userId: Long, realName: String, gender: String, userType: String, classIds: List<Long>): Boolean {
        val classIdsString = classIds.joinToString("#")
        val user = User(
            id = userId,
            realName = realName,
            gender = Gender.valueOf(gender.uppercase()),
            userType = UserType.valueOf(userType.uppercase()),
            classIds = classIdsString,
            accountStatus = AccountStatus.PENDING
        )
        return userMapper.updateProfile(user) > 0
    }
    
    // 兼容方法：单个班级ID转换为列表
    override fun completeProfile(userId: Long, realName: String, gender: String, userType: String, classId: Long?): Boolean {
        val classIds = if (classId != null) listOf(classId) else emptyList()
        return completeProfile(userId, realName, gender, userType, classIds)
    }

    override fun approveUser(userId: Long): Boolean {
        return userMapper.updateStatus(userId, "APPROVED", true, LocalDateTime.now().toString()) > 0
    }

    override fun rejectUser(userId: Long): Boolean {
        return userMapper.updateStatus(userId, "REJECTED", false, null) > 0
    }

    override fun getPendingUsers(): Map<String, List<User>> {
        return mapOf(
            "students" to userMapper.findPendingStudents(),
            "teachers" to userMapper.findPendingTeachers()
        )
    }

    override fun getAllUsers(): List<User> {
        return userMapper.findAllUsers()
    }

    override fun searchUsersByRealName(realName: String): List<User> {
        return userMapper.searchByRealName(realName)
    }

    override fun getUsersByStatus(status: String): List<User> {
        return userMapper.findByStatus(status)
    }

    override fun updateLastLoginTime(openid: String): Boolean {
        return userMapper.updateLastLoginTime(openid) > 0
    }

    override fun getUserById(id: Long): User? {
        return userMapper.findById(id)
    }

    override fun getUsersByClassId(classId: Long): List<User> {
        return userMapper.findStudentsByClassId(classId)
    }

    override fun getUsersByType(userType: String): List<User> {
        return userMapper.findByUserType(userType)
    }

    @Transactional
    override fun deleteUser(userId: Long): Boolean {
        logger.info("开始删除用户: userId={}", userId)
        
        try {
            // 获取用户信息
            val user = userMapper.findById(userId) ?: run {
                logger.warn("用户不存在: userId={}", userId)
                return false
            }
            
            logger.info("删除用户: userId={}, realName={}, openid={}", userId, user.realName, user.openid)
            
            // 1. 获取并删除用户的所有练习记录（包括COS音频文件）
            val exerciseRecords = exerciseRecordService.findByUserId(userId)
            logger.info("找到 {} 条练习记录需要删除", exerciseRecords.size)
            
            exerciseRecords.forEach { record ->
                logger.info("删除练习记录: recordId={}", record.id)
                val deleteSuccess = exerciseRecordService.delete(record.id)
                if (!deleteSuccess) {
                    logger.warn("删除练习记录失败: recordId={}", record.id)
                }
            }
            
            // 2. 删除用户会话记录（根据openid和userId）
            logger.info("删除用户会话记录")
            user.openid?.let { openid ->
                userSessionMapper.deactivateByOpenid(openid)
            }
            userSessionMapper.deactivateByUserId(userId)
            
            // 3. 删除用户主记录
            logger.info("删除用户主记录")
            val deleteResult = userMapper.deleteById(userId)
            
            val success = deleteResult > 0
            logger.info("用户删除结果: {}", if (success) "成功" else "失败")
            return success
            
        } catch (e: Exception) {
            logger.error("删除用户失败: userId={}", userId, e)
            throw RuntimeException("删除用户失败: ${e.message}", e)
        }
    }
}